package org.elanfox.cloud.common.enums.base;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.SneakyThrows;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author allan
 * @version 1.0.0
 * @date 2021/3/11
 */
public class CodeDescEnumJsonDeserializer extends JsonDeserializer<CodeDescCommonEnum> {
    @SneakyThrows
    @Override
    public CodeDescCommonEnum deserialize(JsonParser jp, DeserializationContext context) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String currentName = jp.currentName();
        if (node == null) {
            return null;
        }

        Field field = FieldUtils.getDeclaredField(jp.getCurrentValue().getClass(), currentName, true);
        while (field == null) {
            Class<?> type = jp.getCurrentValue().getClass().getSuperclass();
            if (type == null) {
                throw new Exception();
            }
            field = FieldUtils.getDeclaredField(type, currentName, true);
        }
        JsonNode valNode = node.get("code");
        if (valNode.isInt()) {
            return CodeDescEnumHelper.getEnumTypeByCode(field.getType(), valNode.asInt());
        }
        if (valNode.isTextual()) {
            return CodeDescEnumHelper.getEnumTypeByCode(field.getType(), valNode.asText());
        }

        throw new Exception();
    }
}
